<template>
  <div class="comment-container">
    <!-- 一级评论编辑框 -->
    <div class="comment-editor">
      <el-input
        type="textarea"
        rows="4"
        v-model="newComment"
        placeholder="留下你的评论..."
        @keyup.enter.native.prevent="handleSubmitComment"
        class="editor-input"
      />
      <div class="editor-footer">
        <el-button
          type="primary"
          :disabled="!newComment.trim() || submitting"
          @click="handleSubmitComment"
          class="submit-button"
        >
          {{ submitting ? "发布中..." : "发布评论" }}
        </el-button>
      </div>
    </div>

    <!-- 评论列表 -->
    <div class="comment-list">
      <div v-if="loading" class="loading">评论加载中...</div>

      <div v-else-if="comments.length === 0" class="empty">
        <p>目前还没有评论，快来发表你的看法吧！</p>
      </div>

      <transition-group name="fade" tag="div">
        <div v-for="comment in comments" :key="comment.id" class="comment-card">
          <img class="avatar" :src="comment.avatar" alt="头像"/>
          <div class="content">
            <div class="info">
              <span class="username">{{ comment.username }}</span>
              <span class="meta">{{ formatTime(comment.gmtCreate) }}</span>
            </div>
            <p class="text">{{ comment.content }}</p>
            <div class="actions">
              <el-button type="text" class="like">
                <i class="el-icon-thumb"></i> {{ comment.likeCount || 0 }}
              </el-button>
              <el-button
                type="text"
                class="reply"
                @click="toggleReplyInput(comment)"
              >
                回复
              </el-button>
            </div>

            <!-- 回复切换按钮 -->
            <div v-if="comment.children && comment.children.length" class="show-replies-btn-wrapper">
              <el-button
                type="text"
                class="show-replies-btn"
                @click="toggleReplies(comment)"
              >
                {{
                  comment.showReplies
                    ? `收起回复 (${comment.children.length})`
                    : `共 ${comment.children.length} 条回复，点击查看`
                }}
                <i
                  :class="[
                    'el-icon-arrow-down',
                    comment.showReplies ? 'rotate' : '',
                  ]"
                />
              </el-button>
            </div>

            <!-- 二级评论区 -->
            <transition name="fade">
              <div v-if="comment.showReplies" class="reply-section">
                <!-- 回复输入框 -->
                <div class="reply-editor" v-show="comment.showReplyInput">
                  <el-input
                    type="textarea"
                    v-model="comment.replyInput"
                    rows="2"
                    placeholder="写下你的回复..."
                    @keyup.enter.native.prevent="handleSubmitReply(comment)"
                  />
                  <div class="editor-footer">
                    <el-button
                      size="mini"
                      type="primary"
                      :loading="comment.replySubmitting"
                      :disabled="!comment.replyInput.trim() || comment.replySubmitting"
                      @click="handleSubmitReply(comment)"
                    >
                      回复
                    </el-button>
                    <el-button size="mini" @click="cancelReply(comment)" :disabled="comment.replySubmitting">取消
                    </el-button>
                  </div>
                </div>

                <!-- 二级评论列表 -->
                <div class="replies">
                  <div
                    v-for="reply in comment.children"
                    :key="reply.id"
                    class="reply-card"
                  >
                    <img class="avatar" :src="reply.avatar" alt="头像"/>
                    <div class="content">
                      <div class="info">
                        <span class="username">{{ reply.username }}</span>
                        <span class="meta">{{ formatTime(reply.gmtCreate) }}</span>
                      </div>
                      <p class="text">{{ reply.content }}</p>
                      <div class="actions">
                        <el-button type="text" class="like">
                          <i class="el-icon-thumb"></i> {{ reply.likeCount || 0 }}
                        </el-button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </transition>
          </div>
        </div>
      </transition-group>

      <el-button
        v-if="hasMore"
        :loading="loading"
        @click="loadMore"
        class="load-more"
      >
        {{ loading ? "加载中..." : "查看更多评论" }}
      </el-button>
    </div>
  </div>
</template>

<script>
import commentApi from "@/api/comment";

export default {
  props: {
    targetId: {type: String, required: true},
    targetType: {type: String, required: true},
  },
  data() {
    return {
      newComment: "",
      comments: [],  // 一级评论列表，带children数组（二级评论）
      submitting: false,
      loading: false,
      currentPage: 1,
      pageSize: 5,
      hasMore: true,
    };
  },
  created() {
    this.fetchComments();
  },
  methods: {
    // 初始化评论
    initCommentFields(comment, indexOffset = 0) {
      comment.floor = indexOffset + 1;
      comment.showReplies = false;
      comment.showReplyInput = false;
      comment.replyInput = "";
      comment.replySubmitting = false;
      comment.children = comment.children || [];
      // 初始化二级评论字段
      comment.children.forEach((reply) => {
        reply.showReplies = false;
        reply.showReplyInput = false;
        reply.replyInput = "";
        reply.replySubmitting = false;
      });
    },

    async fetchComments() {
      if (this.loading) return;
      this.loading = true;
      try {
        const res = await commentApi.findAllComment(
          this.currentPage,
          this.pageSize,
          this.targetId,
          this.targetType
        );
        const responseData = res.data.data;
        const list = responseData.records || [];

        list.forEach((comment, i) => {
          this.initCommentFields(comment, (this.currentPage - 1) * this.pageSize + i);
        });

        this.comments = [...this.comments, ...list];
        this.hasMore = responseData.current < responseData.pages;
        this.currentPage++;
      } catch (error) {
        console.error("评论加载失败", error);
      } finally {
        this.loading = false;
      }
    },

    formatTime(time) {
      const date = new Date(time);
      const diff = (Date.now() - date.getTime()) / 1000;

      const pad = (n) => (n < 10 ? '0' + n : n);
      const hours = pad(date.getHours());
      const minutes = pad(date.getMinutes());
      const hhmm = `${hours}:${minutes}`;

      if (diff < 60) return `刚刚 · ${hhmm}`;
      if (diff < 3600) return `${Math.floor(diff / 60)}分钟前 ${hhmm}`;
      if (diff < 86400) return `${Math.floor(diff / 3600)}小时前 ${hhmm}`;
      return `${date.toLocaleDateString().replace(/\//g, "-")}  ${hhmm}`;
    },

    toggleReplies(comment) {
      comment.showReplies = !comment.showReplies;
      if (!comment.showReplies) {
        comment.showReplyInput = false;
        comment.replyInput = "";
      }
    },

    toggleReplyInput(comment) {
      comment.showReplyInput = true;
      if (!comment.showReplies) {
        comment.showReplies = true;
      }
    },

    cancelReply(comment) {
      comment.replyInput = "";
      comment.showReplyInput = false;
    },

    loadMore() {
      this.fetchComments();
    },

    // 重新计算所有一级评论楼层
    refreshFloor() {
      this.comments.forEach((c, i) => {
        c.floor = i + 1;
      });
    },

    // 一级评论提交
    async handleSubmitComment() {
      if (!this.newComment.trim()) return;
      this.submitting = true;
      try {
        const params = {
          content: this.newComment.trim(),
          parentId: "0",
          targetId: this.targetId,
          targetType: this.targetType,
        };
        const res = await commentApi.submitComment(params);
        const newComment = res.data.data || res.data;

        // 初始化新评论字段
        this.initCommentFields(newComment);

        // 插入头部
        this.comments.unshift(newComment);

        // 重新计算楼层
        this.refreshFloor();

        // 触发响应式刷新，替换数组（避免Vue渲染异常）
        this.comments = [...this.comments];

        this.newComment = "";
        this.$message.success("发布评论成功！");
      } catch (err) {
        console.error("发布一级评论失败", err);
        this.$message.error("发布评论失败，请稍后重试");
      } finally {
        this.submitting = false;
      }
    },

    // 二级评论提交
    async handleSubmitReply(parentComment) {
      if (!parentComment.replyInput.trim()) return;
      parentComment.replySubmitting = true;
      try {
        const params = {
          content: parentComment.replyInput.trim(),
          parentId: parentComment.id,
          targetId: this.targetId,
          targetType: this.targetType,
        };
        const res = await commentApi.submitComment(params);
        const newReply = res.data.data || res.data;

        // 初始化二级评论字段
        newReply.showReplies = false;
        newReply.showReplyInput = false;
        newReply.replyInput = "";
        newReply.replySubmitting = false;
        newReply.children = [];

        // 确保children数组响应式
        if (!parentComment.children) {
          this.$set(parentComment, "children", []);
        }

        // 插入头部
        parentComment.children.unshift(newReply);

        // 触发Vue响应式刷新
        parentComment.children = [...parentComment.children];

        // 清空输入框并关闭
        parentComment.replyInput = "";
        parentComment.showReplyInput = false;
        parentComment.showReplies = true;
        this.$message.success("发布评论成功！");
      } catch (err) {
        console.error("发布回复失败", err);
        this.$message.error("回复失败，请稍后重试");
      } finally {
        parentComment.replySubmitting = false;
      }
    },
  },
};
</script>

<style scoped>
.comment-container {
  max-width: 960px;
  margin-left: 16px;
  padding: 20px 0;
  font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
  color: #333;
}

.comment-editor {
  background: #ffffff;
  padding: 20px 20px 12px;
  border-radius: 14px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.editor-input >>> .el-textarea__inner {
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 12px;
  font-size: 14px;
  padding: 14px;
  resize: vertical;
  transition: all 0.2s ease-in-out;
}

.editor-input >>> .el-textarea__inner:focus {
  border-color: #409eff;
  background: #fff;
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.15);
}

.editor-footer {
  text-align: right;
  margin-top: 10px;
}

.submit-button {
  background-color: #409eff;
  border: none;
  border-radius: 20px;
  padding: 6px 24px;
  font-weight: 600;
}

.submit-button:hover {
  background-color: #66b1ff;
}

.comment-list {
  background: #fff;
  padding: 16px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(78, 172, 255, 0.05);
}

.comment-card {
  display: flex;
  padding: 12px 0;
  border-bottom: 1px solid #f0f2f7;
  gap: 12px;
}

.comment-card:last-child {
  border-bottom: none;
}

.avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  border: 2px solid #eaf6ff;
  box-shadow: 0 0 0 1px #4eacff;
}

.content {
  flex: 1;
}

.info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
  font-size: 13px;
  color: #888;
}

.username {
  font-weight: 600;
  color: #4eacff;
}

.meta {
  font-size: 14px;
  color: #aaa;
}

.text {
  font-size: 15px !important;
  margin: 6px 0;
  line-height: 1.6;
  word-break: break-word;
}

.actions {
  display: flex;
  gap: 16px;
  font-size: 13px;
  color: #666;
}

.like:hover,
.reply:hover {
  color: #4eacff;
}

.show-replies-btn-wrapper {
  margin-top: 8px;
}

.show-replies-btn {
  font-size: 16px;
  color: #4eacff;
  padding: 0;
  user-select: none;
  display: inline-flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
}

.show-replies-btn i {
  transition: transform 0.3s ease;
  font-size: 14px;
}

.show-replies-btn i.rotate {
  transform: rotate(180deg);
}

.reply-section {
  margin-top: 12px;
  padding-left: 56px;
  border-left: 2px dashed #e0f0ff;
}

.reply-editor {
  margin-bottom: 12px;
}

.replies {
  margin-top: 12px;
}

.reply-card {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

.reply-card .content {
  flex: 1;
}

.actions {
  /* 通用actions样式 */
  font-size: 13px;
  color: #666;
  display: flex;
  gap: 16px;
}

.reply-card .actions {
  margin-top: 4px;
}

.load-more {
  margin-top: 12px;
  width: 100%;
  border-radius: 24px;
  background-color: #f0f8ff;
  color: #4eacff;
  border-color: #e0f0ff;
}

.load-more:hover {
  background-color: #e0f5ff;
}

.fade-enter-active,
.fade-leave-active {
  transition: all 0.3s ease;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
  transform: translateY(8px);
}
</style>
